# -*- coding: utf-8 -*-
# standard
import os
import sys
from platform import system
from queue import Queue
import argparse

# third

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from models import *


"""
@Title:  解析和下载视频的函数 
@File: parse_and_download.py
@Author: walle 2023年10日18日 11时44分21秒
@Version: 1.0.0
@Desc: 
"""


def read_raw_videos_from_json():
    """
    从json文件中读取待下载的视频信息写入数据库
    """
    # 目前仅仅 all_paths 指定的文件
    sys_name = system().lower()
    if sys_name == "windows":
        all_paths = [os.path.join(_P_PATH, "demo_json", "hdvg_3_filter.json")]
    else:
        all_paths = [os.path.join(_P_PATH, "raw_json", "hdvg_head_filter.json")]
    logger.warning(f"{sys_name}操作系统，加载 {all_paths[0]}文件")
    RawJsonHandler.read_json_data(all_path=all_paths)


def download_videos_forever(limit: int = 1):
    """
    持续的下载视频。
    :param limit: 做多下载多少个视频？默认是1个， -1表示不限制
    """
    need_download_videos = RawVideoObjectOrm.get_all_videos_from_db()
    logger.debug(f"本批次有{len(need_download_videos)}个视频需要下载")
    num = 0
    for item in need_download_videos:
        num += 1
        if limit < 0:  # 表示不做限制
            pass
        else:
            if num > limit:
                break
        key = item['key']
        file = VideoFile(download_url=item['url'], key=key)
        resp = file.download(re_download=False)
        if resp:
            file.save_orm(db_handler=new_db_session())          
            sources = file.save_paths
            logger.info(f"第{num}个视频({key})的{len(sources)}个文件开始拷贝")
            if len(sources) > 0:
                ScpRecordOrm.batch_copy(sources=sources)
            logger.info(f"第{num}个视频({key})的{len(sources)}个文件拷贝完毕")  
        else:
            logger.error(f"第{num}个视频({key})的下载失败, 原因: {resp.message}")




def run_by_args():
    """
    使用命令行参数选择要执行的程序，临时使用
    """
    print(f"请选择下面的序号输入执行对应的程序:")
    print(f"1. 解析json文件并写入数据库")
    print(f"2. 从数据库读取待拉取的视频信息下载第一个")
    print(f"3. 从数据库读取待拉取的视频信息下载100个")
    args = input()
    if args == "1":
        print("开始执行 read_raw_videos_from_json")
        read_raw_videos_from_json()
    elif args == "2":
        print("开始执行 download_videos_forever 1")
        download_videos_forever()
    elif args == "3":
        print("开始执行 download_videos_forever 100")
        download_videos_forever(100)
    else:
        print("88")


if __name__ == '__main__':
    run_by_args()
    pass